package com.example.filedemo;

import android.content.Context;

import java.io.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static android.content.Context.MODE_PRIVATE;

public class FileSaveQQ {
    // 读取用户信息
    public static Map<String,String> getUserInfo(Context context){
        try {
            FileInputStream fis = context.openFileInput("data.txt");
            byte[] buffer = new byte[1024];
            int len = fis.read(buffer); // 将文件中的数据以字节为单位，存放到buffer。读取的数据字节数为len
            String s = new String(buffer,0,len);
            String[] split = s.split(":");
            HashMap<String,String> userMap = new HashMap<>();
            userMap.put("account",split[0]);
            userMap.put("password",split[1]);
            return userMap;


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }catch (Exception e){
            return null;
        }

    }
    // 保存用户信息
    public static boolean saveUserInfo(Context context,
                                       String account,
                                       String password){
        // 创建fos对象，
        FileOutputStream fos=null;
        try {
            fos = context.openFileOutput("data.txt", MODE_PRIVATE);
            String content = account+":"+password;
            fos.write(content.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }

            }
            return true;
        }
    }

}
